<template>
  <div class="project-edit p-4">
    <el-card class="box-card">
      <template #header>
        <div class="card-header flex items-center justify-between">
          <h2 class="text-xl font-bold">编辑项目</h2>
          <el-button @click="goBack">返回</el-button>
        </div>
      </template>
      
      <div v-loading="loading">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="mt-6"
        >
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入项目名称" />
          </el-form-item>
          
          <el-form-item label="项目类型">
            <el-tag :type="project.type === ProjectType.FRONTEND ? 'success' : 'info'">
              {{ project.type === ProjectType.FRONTEND ? '前端' : '后端' }}
            </el-tag>
            <span class="ml-2 text-gray-400">(项目类型创建后不可修改)</span>
          </el-form-item>
          
          <el-form-item label="项目状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择项目状态" class="w-64">
              <el-option label="开发中" :value="ProjectStatus.DEVELOPMENT" />
              <el-option label="激活" :value="ProjectStatus.ACTIVE" />
              <el-option label="停用" :value="ProjectStatus.INACTIVE" />
              <el-option label="已废弃" :value="ProjectStatus.DEPRECATED" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="代码仓库" prop="git_url">
            <el-input v-model="form.git_url" placeholder="请输入代码仓库地址" />
          </el-form-item>
          
          <el-form-item label="项目描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="请输入项目描述"
            />
          </el-form-item>
          
          <el-form-item label="启动脚本" prop="startup_script">
            <el-input
              v-model="form.startup_script"
              type="textarea"
              :rows="8"
              placeholder="请输入项目启动脚本"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
            <el-button @click="resetForm(formRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type UploadUserFile } from 'element-plus'
import { getProject, updateProject } from '@/request/project-api'
import { ProjectType, ProjectStatus, type Project, type ProjectUpdateRequest } from '@/model/project-model'

defineOptions({
  name: 'ProjectEdit'
})

const route = useRoute()
const router = useRouter()
const projectId = route.params.id as string
const formRef = ref<FormInstance>()

// 项目数据
const loading = ref(true)
const project = reactive<Project>({
  id: 0, // 改为number类型
  name: '',
  type: ProjectType.FRONTEND,
  status: ProjectStatus.DEVELOPMENT, // 修正为有效的枚举值
  created_at: '', // 修正为Project接口中的属性名
  updated_at: '' // 修正为Project接口中的属性名
})

// 表单数据
const form = reactive<{
  name: string
  status: ProjectStatus
  description: string
  git_url: string
  startup_script: string
  file: File | null
  configFile: File | null
}>({
  name: '',
  status: ProjectStatus.DEVELOPMENT,
  description: '',
  git_url: '',
  startup_script: '',
  file: null,
  configFile: null
})

// 文件列表
const fileList = ref<UploadUserFile[]>([])
const configFileList = ref<UploadUserFile[]>([])

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }]
}

// 获取项目详情
const fetchProjectDetail = async () => {
  loading.value = true
  try {
    const response = await getProject(Number(projectId)) // 转换为数字
    if (response.code === 0) { // 使用code而非success
      const data = response.data
      Object.assign(project, data)
      
      // 填充表单数据
      form.name = data.name
      form.status = data.status
      form.description = data.description || ''
      form.git_url = data.git_url || ''
      form.startup_script = data.startup_script || ''
      
      // 如果有版本信息，显示最新版本到文件列表
      if (data.versions && data.versions.length > 0) {
        const currentVersion = data.versions.find(v => v.is_current) || data.versions[0]
        fileList.value = [
          {
            name: `版本 ${currentVersion.version}`,
            url: ''
          }
        ]
      }
      
      // 如果有配置模板，显示在文件列表中
      if (data.config_template) {
        configFileList.value = [
          {
            name: typeof data.config_template === 'string' 
              ? data.config_template
              : `配置 (ID: ${data.config_template.id || 'N/A'})`,
            url: ''
          }
        ]
      }
    } else {
      ElMessage.error(response.errorMsg || '获取项目详情失败')
    }
  } catch (error) {
    console.error('获取项目详情失败:', error)
    ElMessage.error('获取项目详情失败')
  } finally {
    loading.value = false
  }
}

// 处理项目文件变更
const handleFileChange = (file: UploadUserFile) => {
  form.file = file.raw as File
}

// 处理配置文件变更
const handleConfigFileChange = (file: UploadUserFile) => {
  form.configFile = file.raw as File
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  
  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true
      
      try {
        // 构造更新请求
        const updateData: ProjectUpdateRequest = {
          id: Number(projectId), // 确保是数字类型
          name: form.name,
          status: form.status,
          description: form.description,
          git_url: form.git_url,
          startup_script: form.startup_script // 添加启动脚本字段
        }
        
        // 注意：ProjectUpdateRequest接口中没有file和configFile属性
        // 这里可能需要另外的API调用来上传文件
        // 暂时跳过文件处理逻辑
        
        const response = await updateProject(updateData)
        
        if (response.code === 0) { // 使用code而非success
          ElMessage.success('保存成功')
          router.push(`/project/detail/${projectId}`)
        } else {
          ElMessage.error(response.errorMsg || '保存失败')
        }
      } catch (error) {
        console.error('更新项目失败:', error)
        ElMessage.error('更新项目失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  
  // 重新填充表单数据
  form.name = project.name
  form.status = project.status
  form.description = project.description || ''
  form.git_url = project.git_url || '' // 修正为git_url
  form.startup_script = project.startup_script || ''
  form.file = null
  form.configFile = null
  
  // 重置文件列表
  if (project.versions && project.versions.length > 0) {
    const currentVersion = project.versions.find(v => v.is_current) || project.versions[0]
    fileList.value = [
      {
        name: `版本 ${currentVersion.version}`,
        url: ''
      }
    ]
  } else {
    fileList.value = []
  }
  
  if (project.config_template) {
    configFileList.value = [
      {
        name: typeof project.config_template === 'string' 
          ? project.config_template 
          : `配置 (ID: ${project.config_template.id || 'N/A'})`,
        url: ''
      }
    ]
  } else {
    configFileList.value = []
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  fetchProjectDetail()
})
</script>

<style scoped lang="scss">
.project-edit {
  .el-form {
    max-width: 800px;
  }
}
</style>
